'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/auth-context'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { User, Calendar, Mail, Shield, Settings } from 'lucide-react'
import { userApi } from '@/lib/api-client'

interface UserData {
  id: string
  email: string
  name: string
  avatar?: string
  bio?: string
  website?: string
  role: 'USER' | 'ADMIN'
  createdAt: string
  _count?: {
    tools: number
    reviews: number
    favorites: number
  }
}

interface UserProfileProps {
  onEditProfile?: () => void
}

export function UserProfile({ onEditProfile }: UserProfileProps = {}) {
  const { user: authUser, loading: authLoading } = useAuth()
  const [user, setUser] = useState<UserData | null>(null)
  const [loading, setLoading] = useState(true)


  useEffect(() => {
    if (!authLoading) {
      if (authUser) {
        fetchUserProfile(authUser.id)
      } else {
        setLoading(false)
      }
    }
  }, [authUser, authLoading])



  const fetchUserProfile = async (userId: string) => {
    try {
      setLoading(true)
      // 使用API客户端获取用户资料
      const result = await userApi.getProfile()

      if (result.success) {
        // 确保返回的数据包含_count属性，如果没有则添加默认值
        const userData = result.data
        if (!userData._count) {
          userData._count = {
            tools: 0,
            reviews: 0,
            favorites: 0
          }
        }
        setUser(userData)
      } else {
        // 如果详细信息不存在，使用认证用户的基本信息
        const basicUser: UserData = {
          id: authUser!.id,
          email: authUser!.email,
          name: authUser!.name,
          avatar: authUser!.avatar,
          role: authUser!.role,
          createdAt: new Date().toISOString(),
          _count: {
            tools: 0,
            reviews: 0,
            favorites: 0
          }
        }
        setUser(basicUser)
      }
    } catch (error) {
      console.error('获取用户资料失败:', error)
      // 使用认证用户的基本信息
      if (authUser) {
        const basicUser: UserData = {
          id: authUser.id,
          email: authUser.email,
          name: authUser.name,
          avatar: authUser.avatar,
          role: authUser.role,
          createdAt: new Date().toISOString(),
          _count: {
            tools: 0,
            reviews: 0,
            favorites: 0
          }
        }
        setUser(basicUser)
      }
    } finally {
      setLoading(false)
    }
  }

  if (authLoading || loading) {
    return (
      <Card>
        <CardContent className="p-6">
          <div className="flex items-center gap-4">
            <Skeleton className="h-16 w-16 rounded-full" />
            <div className="flex-1 space-y-2">
              <Skeleton className="h-6 w-1/3" />
              <Skeleton className="h-4 w-1/2" />
              <Skeleton className="h-4 w-1/4" />
            </div>
            <Skeleton className="h-8 w-16" />
          </div>

          <div className="mt-6 grid grid-cols-3 gap-4">
            <div className="text-center">
              <Skeleton className="h-8 w-8 mx-auto mb-2" />
              <Skeleton className="h-4 w-12 mx-auto" />
            </div>
            <div className="text-center">
              <Skeleton className="h-8 w-8 mx-auto mb-2" />
              <Skeleton className="h-4 w-12 mx-auto" />
            </div>
            <div className="text-center">
              <Skeleton className="h-8 w-8 mx-auto mb-2" />
              <Skeleton className="h-4 w-12 mx-auto" />
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  if (!authUser || !user) {
    return (
      <Card>
        <CardContent className="p-6 text-center">
          <p className="text-gray-500">请先登录以查看个人信息</p>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardContent className="p-6">
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-4">
            {/* 用户头像 */}
            <div className="h-16 w-16 bg-gradient-to-br from-blue-50 to-indigo-100 rounded-full flex items-center justify-center">
              {user.avatar ? (
                <img 
                  src={user.avatar} 
                  alt={user.name}
                  className="h-16 w-16 rounded-full object-cover"
                />
              ) : (
                <User className="h-8 w-8 text-blue-400" />
              )}
            </div>

            {/* 用户信息 */}
            <div>
              <div className="flex items-center gap-2 mb-1">
                <h2 className="text-xl font-semibold text-gray-900">{user.name}</h2>
                {user.role === 'ADMIN' && (
                  <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                    <Shield className="h-3 w-3 mr-1" />
                    管理员
                  </span>
                )}
              </div>
              
              <div className="flex items-center gap-4 text-sm text-gray-600">
                <div className="flex items-center gap-1">
                  <Mail className="h-4 w-4" />
                  {user.email}
                </div>
                <div className="flex items-center gap-1">
                  <Calendar className="h-4 w-4" />
                  加入于 {new Date(user.createdAt).toLocaleDateString()}
                </div>
              </div>

              {/* 统计信息 */}
              <div className="flex items-center gap-6 mt-3 text-sm">
                <div className="text-center">
                  <div className="font-semibold text-gray-900">{user._count?.tools || 0}</div>
                  <div className="text-gray-500">发布工具</div>
                </div>
                <div className="text-center">
                  <div className="font-semibold text-gray-900">{user._count?.reviews || 0}</div>
                  <div className="text-gray-500">评价数</div>
                </div>
                <div className="text-center">
                  <div className="font-semibold text-gray-900">{user._count?.favorites || 0}</div>
                  <div className="text-gray-500">收藏数</div>
                </div>
              </div>
            </div>
          </div>

          {/* 编辑提示 */}
          <div className="mt-6 pt-4 border-t border-gray-200">
            <div className="flex items-center justify-center text-sm text-gray-500">
              <Settings className="h-4 w-4 mr-2" />
              <span>要编辑个人资料，请前往</span>
              <button
                onClick={onEditProfile}
                className="ml-1 text-blue-500 hover:text-blue-700 underline"
              >
                设置页面
              </button>
            </div>
          </div>

        </div>
      </CardContent>
    </Card>

  )
}
